<template>
  <div class="contact-message-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="card-header__titles">
            <h1 class="card-title">{{ pageTitle || '客户留言' }}</h1>
            <p v-if="pageSubtitle" class="card-subtitle">{{ pageSubtitle }}</p>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="搜索">
          <el-input
            v-model="searchForm.search"
            placeholder="姓名、邮箱或留言内容"
            clearable
            @clear="handleSearch"
            style="width: 240px;"
          />
        </el-form-item>
        <el-form-item label="类型">
          <el-select
            v-model="searchForm.message_type"
            placeholder="全部"
            clearable
            @clear="handleSearch"
            style="width: 140px;"
          >
            <el-option label="联系我们" value="contact" />
            <el-option label="邮件订阅" value="newsletter" />
            <el-option label="经销商申请" value="reseller" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.is_read"
            placeholder="全部"
            clearable
            @clear="handleSearch"
            style="width: 120px;"
          >
            <el-option label="已读" :value="true" />
            <el-option label="未读" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table
        v-loading="loading"
        :data="messageList"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="类型" width="120">
          <template #default="{ row }">
            <el-tag
              :type="row.message_type === 'contact' ? 'primary' : (row.message_type === 'newsletter' ? 'success' : 'warning')"
            >
              {{ row.message_type_display }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名" width="120">
          <template #default="{ row }">
            {{ row.name || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="message" label="留言内容" min-width="300" show-overflow-tooltip />
        <el-table-column label="已读" width="80" align="center">
          <template #default="{ row }">
            <el-checkbox
              v-model="row.is_read"
              :disabled="row._statusLoading"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleView(row)"
            >
              查看
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.page_size"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="fetchMessages"
        @current-change="fetchMessages"
        style="margin-top: 20px; justify-content: flex-end;"
      />
    </el-card>

    <!-- 查看详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="留言详情"
      width="600px"
    >
      <el-descriptions v-if="currentMessage" :column="1" border>
        <el-descriptions-item label="类型">
          <el-tag
            :type="currentMessage.message_type === 'contact' ? 'primary' : (currentMessage.message_type === 'newsletter' ? 'success' : 'warning')"
          >
            {{ currentMessage.message_type_display }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="姓名">
          {{ currentMessage.name || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="邮箱">
          {{ currentMessage.email }}
        </el-descriptions-item>
        <el-descriptions-item label="留言内容">
          <div style="white-space: pre-wrap;">{{ currentMessage.message }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="currentMessage.is_read ? 'success' : 'info'">
            {{ currentMessage.is_read ? '已读' : '未读' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ formatDate(currentMessage.created_at) }}
        </el-descriptions-item>
        <el-descriptions-item v-if="currentMessage.replied_at" label="回复时间">
          {{ formatDate(currentMessage.replied_at) }}
        </el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button
          v-if="!currentMessage?.is_read"
          type="primary"
          @click="handleMarkRead"
        >
          标记为已读
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { getContactMessages, deleteContactMessage, markContactMessageRead, updateContactMessage } from '@/api/contactMessage'
import type { ContactMessage } from '@/api/contactMessage'
import dayjs from 'dayjs'
import { usePageMeta } from '@/composables/usePageMeta'

// 扩展 ContactMessage 类型以包含加载状态
interface ContactMessageWithLoading extends ContactMessage {
  _statusLoading?: boolean
}

const { pageTitle, pageSubtitle } = usePageMeta()

const loading = ref(false)
const messageList = ref<ContactMessageWithLoading[]>([])
const total = ref(0)
const dialogVisible = ref(false)
const currentMessage = ref<ContactMessage | null>(null)

const searchForm = reactive({
  search: '',
  message_type: undefined as string | undefined,
  is_read: undefined as boolean | undefined
})

const pagination = reactive({
  page: 1,
  page_size: 20
})

const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

const fetchMessages = async () => {
  loading.value = true
  try {
    const params = {
      ...pagination,
      ...searchForm
    }
    const response = await getContactMessages(params)
    messageList.value = response.results || []
    total.value = response.count || 0
  } catch (error) {
    ElMessage.error('获取留言列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  fetchMessages()
}

const handleReset = () => {
  searchForm.search = ''
  searchForm.message_type = undefined
  searchForm.is_read = undefined
  handleSearch()
}

const handleView = (row: ContactMessage) => {
  currentMessage.value = row
  dialogVisible.value = true
  
  // 如果是未读，自动标记为已读
  if (!row.is_read) {
    markContactMessageRead(row.id).then(() => {
      row.is_read = true
    }).catch(() => {
      // 忽略错误
    })
  }
}

const handleMarkRead = async () => {
  if (!currentMessage.value) return
  
  try {
    await markContactMessageRead(currentMessage.value.id)
    currentMessage.value.is_read = true
    ElMessage.success('已标记为已读')
    dialogVisible.value = false
    fetchMessages()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const handleStatusChange = async (row: ContactMessageWithLoading) => {
  row._statusLoading = true
  
  try {
    await updateContactMessage(row.id, { is_read: row.is_read })
    ElMessage.success(row.is_read ? '已标记为已读' : '已标记为未读')
  } catch (error) {
    row.is_read = !row.is_read
    ElMessage.error('状态更新失败')
  } finally {
    row._statusLoading = false
  }
}

const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这条留言吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteContactMessage(id)
    ElMessage.success('删除成功')
    fetchMessages()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

onMounted(() => {
  fetchMessages()
})
</script>

<style scoped lang="scss">
.contact-message-list {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: var(--spacing-lg);
  }

  .card-header__titles {
    display: flex;
    flex-direction: column;
    gap: 4px;
  }

  .card-title {
    margin: 0;
    font-size: var(--font-size-xl);
    font-weight: var(--font-weight-semibold);
    color: var(--color-text-primary);
  }

  .card-subtitle {
    margin: 0;
    font-size: var(--font-size-sm);
    color: var(--color-text-tertiary);
  }

  .search-form {
    margin-bottom: 20px;
  }
}
</style>
